package com.dotflat.training.service.impl;

import com.dotflat.rest.PO.AreableObjectBasePO;
import com.dotflat.rest.service.impl.AreableObjectBaseServiceImpl;
import com.dotflat.training.domain.OTCourse;
import com.dotflat.training.domain.OTCourseBookRecord;
import com.dotflat.training.repository.OTCourseBookRecordRepository;
import com.dotflat.training.repository.OTCourseRepository;
import com.dotflat.training.service.OTCourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
public class OTCourseServiceImpl extends AreableObjectBaseServiceImpl<OTCourse, OTCourseRepository>
        implements OTCourseService {

    @Autowired
    @Override
    public void setBaseRepository(OTCourseRepository repository){
        super.setBaseRepository(repository);
    }

    @Autowired
    private OTCourseBookRecordRepository bookRecordRepository;

    @Override
    protected void parsePageResult(String areaId, String staffId, AreableObjectBasePO param, PageRequest pageRequest, Page<OTCourse> page){
        Page<String> idsPage = page.map(o->o.getId());
        List<String> ids = idsPage.getContent();
        List<OTCourseBookRecord> records = bookRecordRepository.findAllByAreaIdAndStaffIdAndOfflineCourseIdInAndDeletedIsFalse(areaId, staffId, ids);

        Map<String,OTCourseBookRecord> cache = records.stream().collect(Collectors.toMap(OTCourseBookRecord::getOfflineCourseId, o->o));

        page.forEach(o->{
            OTCourseBookRecord record = cache.get(o.getId());
            o.setBooked( record != null ? record.getBooked() : null);
        });
    }

}